import asyncio

from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from loguru import logger
from starlette.responses import JSONResponse

from app.api.api_v1.api import api_router
from app.core.config import settings
from app.core.exceptions import initException, BizException
from app.logger import init_logging
from app.tasks import scheduler
from app.ws.websocket_server import manager


app = FastAPI(
    title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json"
)

initException()

init_logging()


@app.exception_handler(BizException)
async def bizExceptionHandler(request: Request, exc: BizException):
    return JSONResponse(
        status_code=200,
        content={"code": exc.code, "msg": exc.msg, "data": None},
    )


@app.on_event('startup')
def init_scheduler():
    logger.info("定时任务已启动")
    scheduler.start()

@app.websocket("/ws/{token}")
async def websocket_endpoint(websocket: WebSocket, token: str):
    await manager.connect(websocket)
    try:
        while True:
            message = await websocket.receive_text()
            await manager.receive(message, websocket)
            # await manager.send(f"You wrote: {data}", websocket)
            # await manager.broadcast(f"Client #{client_id} says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
    logger.info(f'{websocket.client.host}:{websocket.client.port}连接已关闭,释放线程......')

# Set all CORS enabled origins
# if settings.BACKEND_CORS_ORIGINS:
#     app.add_middleware(
#         CORSMiddleware,
#         allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
#         allow_credentials=True,
#         allow_methods=["*"],
#         allow_headers=["*"],
#     )
# @app.websocket("/ws")
# async def websocket_endpoint(websocket: WebSocket):
#     await websocket.accept()
#     while True:
#         data = await websocket.receive_text()
#         await websocket.send_text(f"Message text was: {data}")

app.include_router(api_router, prefix=settings.API_V1_STR)
